package org.summer.lawyer.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.summer.common.core.utils.MapstructUtils;
import org.summer.common.mybatis.core.page.PageQuery;
import org.summer.common.mybatis.core.page.TableDataInfo;
import org.summer.common.satoken.utils.LoginHelper;
import org.summer.lawyer.domain.Message;
import org.summer.lawyer.domain.bo.message.MessageBo;
import org.summer.lawyer.domain.vo.lawfirm.LawFirmVo;
import org.summer.lawyer.domain.vo.message.MessageVo;
import org.summer.lawyer.domain.vo.spuorder.SpuOrderVo;
import org.summer.lawyer.domain.vo.spuorderassign.SpuOrderAssignVo;
import org.summer.lawyer.domain.vo.wxuser.WxUserVo;
import org.summer.lawyer.mapper.MessageMapper;
import org.summer.lawyer.service.ILawFirmService;
import org.summer.lawyer.service.IMessageService;
import org.summer.lawyer.service.ISpuOrderAssignService;
import org.summer.lawyer.service.IWxUserService;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 站内消息Service业务层处理
 *
 * @author summer
 * @date 2024-07-23
 */
@RequiredArgsConstructor
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {

    private final IWxUserService wxUserService;
    private final ISpuOrderAssignService spuOrderAssignService;
    private final ILawFirmService lawFirmService;

    /**
     * 查询站内消息
     *
     * @param id 主键
     * @return 站内消息
     */
    @Override
    public MessageVo selectMessageVoById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询站内消息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 站内消息分页列表
     */
    @Override
    public TableDataInfo<MessageVo> selectPageList(MessageBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Message> lqw = buildQueryWrapper(bo);
        Page<MessageVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的站内消息列表
     *
     * @param bo 查询条件
     * @return 站内消息列表
     */
    @Override
    public List<MessageVo> selectMessageVoList(MessageBo bo) {
        LambdaQueryWrapper<Message> lqw = Wrappers.lambdaQuery();
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Message> buildQueryWrapper(MessageBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Message> lqw = Wrappers.lambdaQuery();
        lqw.eq(StrUtil.isNotBlank(bo.getTitle()), Message::getTitle, bo.getTitle());
        lqw.eq(StrUtil.isNotBlank(bo.getMsgContent()), Message::getMsgContent, bo.getMsgContent());
        lqw.eq(bo.getReceiverId() != null, Message::getReceiverId, bo.getReceiverId());
        lqw.like(StrUtil.isNotBlank(bo.getReceiverName()), Message::getReceiverName, bo.getReceiverName());
        lqw.eq(StrUtil.isNotBlank(bo.getReceiverAvatar()), Message::getReceiverAvatar, bo.getReceiverAvatar());
        lqw.eq(bo.getOrderId() != null, Message::getOrderId, bo.getOrderId());
        lqw.like(StrUtil.isNotBlank(bo.getSpuName()), Message::getSpuName, bo.getSpuName());
        lqw.eq(StrUtil.isNotBlank(bo.getStatus()), Message::getStatus, bo.getStatus());
        lqw.eq(StrUtil.isNotBlank(bo.getTrackingNumber()), Message::getTrackingNumber, bo.getTrackingNumber());
        lqw.orderByDesc(Message::getId);
        return lqw;
    }

    /**
     * 新增站内消息
     *
     * @param bo 站内消息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(MessageBo bo) {
        Message add = MapstructUtils.convert(bo, Message.class);
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtil.date());
        add.setUpdateTime(DateUtil.date());
        add.setStatus("0");
        if (LoginHelper.getUserId() != null) {
            add.setCreateBy(LoginHelper.getUserId());
            add.setUpdateBy(LoginHelper.getUserId());
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改站内消息
     *
     * @param bo 站内消息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(MessageBo bo) {
        Message update = MapstructUtils.convert(bo, Message.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtil.date());
        if (LoginHelper.getUserId() != null) {
            update.setUpdateBy(LoginHelper.getUserId());
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Message entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除站内消息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Long selectUnReadMessageCount(MessageBo bo) {
        LambdaQueryWrapper<Message> lqw = Wrappers.lambdaQuery();
        lqw.eq(Message::getReceiverId, bo.getReceiverId());
        lqw.eq(Message::getStatus, "0");
        return baseMapper.selectCount(lqw);
    }

    @Override
    public void markAsRead(List<Long> ids) {
        if (CollUtil.isNotEmpty(ids)) {
            LambdaQueryWrapper<Message> lqw = Wrappers.lambdaQuery();
            lqw.in(Message::getId, ids);
            List<MessageVo> vos = baseMapper.selectVoList(lqw);
            if (CollUtil.isNotEmpty(vos)) {
                for (MessageVo vo : vos) {
                    MessageBo bo = new MessageBo();
                    BeanUtils.copyProperties(vo, bo);
                    bo.setStatus("1");
                    this.updateByBo(bo);
                }
            }
        }
    }

    /**
     * 用户订单通知
     */
    @Override
    public void userOrderMsg(SpuOrderVo vo) {
        WxUserVo wxUserVo = wxUserService.selectWxUserById(vo.getUserId());
        if (wxUserVo != null) {
            String msg = StrUtil.format("尊敬的{}，你的需求我们已经收到小咕正在帮您匹配律师。", wxUserVo.getNickname());
            MessageBo bo = new MessageBo();
            bo.setTitle("用户订单通知");
            bo.setMsgContent(msg);
            bo.setReceiverId(wxUserVo.getWxUserId());
            bo.setReceiverName(wxUserVo.getNickname());
            bo.setReceiverAvatar(wxUserVo.getAvatar());
            bo.setOrderId(vo.getOrderId());
            bo.setSpuName(vo.getSpuName());
            this.insertByBo(bo);
        }

    }

    @Override
    public void userFileOrderMsg(SpuOrderVo vo) {
        WxUserVo wxUserVo = wxUserService.selectWxUserById(vo.getUserId());
        if (wxUserVo != null) {
            String msg = StrUtil.format("尊敬的{}，你下单的{}文书已发送成功，请及时查看邮箱。", wxUserVo.getNickname(), vo.getSpuName());
            MessageBo bo = new MessageBo();
            bo.setTitle("用户文书模版");
            bo.setMsgContent(msg);
            bo.setReceiverId(wxUserVo.getWxUserId());
            bo.setReceiverName(wxUserVo.getNickname());
            bo.setReceiverAvatar(wxUserVo.getAvatar());
            bo.setOrderId(vo.getOrderId());
            bo.setSpuName(vo.getSpuName());
            this.insertByBo(bo);
        }
    }

    /**
     * 用户分配律师
     */
    @Override
    public void assignLawFirmMsg(SpuOrderAssignVo vo) {
        String msg = StrUtil.format("尊敬的{}，你提交的{}已经由{}律师接收，{}律师将在第一时间会与您联系，请保持电话畅通。", vo.getUserName(), vo.getSpuName(), vo.getLawFirmName(), vo.getLawFirmName());
        WxUserVo wxUserVo = wxUserService.selectWxUserById(vo.getUserId());
        if(wxUserVo != null) {
            MessageBo bo = new MessageBo();
            bo.setTitle("用户分配律师");
            bo.setMsgContent(msg);
            bo.setReceiverId(wxUserVo.getWxUserId());
            bo.setReceiverName(wxUserVo.getNickname());
            bo.setReceiverAvatar(wxUserVo.getAvatar());
            bo.setOrderId(vo.getOrderId());
            bo.setSpuName(vo.getSpuName());
            this.insertByBo(bo);
        }

    }

    /**
     * 用户重新分配通知
     * 尊敬的${name}，由于${companyName}律师没有及时回应，我们已经重新安排${lsName}律师接收你的服务，律师会尽快与您联系，敬请谅解。
     */
    @Override
    public void reallocateLawFirmMsg(SpuOrderAssignVo vo) {
        SpuOrderAssignVo lastSpuOrderAssignVo = spuOrderAssignService.selectLastInactiveSpuOrderAssign(vo.getOrderId());
        if(lastSpuOrderAssignVo != null){
            String msg = StrUtil.format("尊敬的{}，由于{}律师没有及时回应，我们已经重新安排{}律师接收你的服务，律师会尽快与您联系，敬请谅解。", vo.getUserName(), lastSpuOrderAssignVo.getLawFirmName(), vo.getLawFirmName());
            WxUserVo wxUserVo = wxUserService.selectWxUserById(vo.getUserId());
            if(wxUserVo != null) {
                MessageBo bo = new MessageBo();
                bo.setTitle("用户重新分配通知");
                bo.setMsgContent(msg);
                bo.setReceiverId(wxUserVo.getWxUserId());
                bo.setReceiverName(wxUserVo.getNickname());
                bo.setReceiverAvatar(wxUserVo.getAvatar());
                bo.setOrderId(vo.getOrderId());
                bo.setSpuName(vo.getSpuName());
                this.insertByBo(bo);
            }
        }

    }

    /**
     * 律师订单通知
     * 尊敬的${companyName}律师，您有新订单，客户${username}在咕法网平台上购买了${order}服务，请进入商家页面查看订单详情。
     */
    @Override
    public void lawFirmOrderMsg(SpuOrderAssignVo vo) {
        String msg = StrUtil.format("尊敬的{}律师，您有新订单，客户{}在咕法网平台上购买了{}服务，请进入商家页面查看订单详情。", vo.getLawFirmName(), vo.getUserName(), vo.getSpuName());
        //WxUserVo wxUserVo = wxUserService.selectWxUserById(vo.g);
        LawFirmVo lawFirmVo = lawFirmService.selectLawFirmVoById(vo.getLawFirmId());
        if(lawFirmVo != null) {
            MessageBo bo = new MessageBo();
            bo.setTitle("律师订单通知");
            bo.setMsgContent(msg);
            bo.setReceiverId(lawFirmVo.getWxUserId());
            bo.setReceiverName(lawFirmVo.getLawFirmName());
            bo.setReceiverAvatar(lawFirmVo.getLawFirmLogo());
           // bo.setOrderId(vo.getOrderId());
            bo.setOrderId(Long.parseLong(vo.getTrackingNumber()));
            bo.setSpuName(vo.getSpuName());
            this.insertByBo(bo);
        }
    }

    /**
     * 用户订单完成
     * 尊敬的${name}，你的订单已完成，请点击此处完成对${companyName}律师的评价，您的建议对我们非常重要。
     */
    @Override
    public void completedOrderMsg(SpuOrderAssignVo vo) {
        String msg = StrUtil.format("尊敬的{}，你的订单已完成，请点击此处完成对{}律师的评价，您的建议对我们非常重要。", vo.getUserName(), vo.getLawFirmName());
        WxUserVo wxUserVo = wxUserService.selectWxUserById(vo.getUserId());
        if(wxUserVo != null) {
            MessageBo bo = new MessageBo();
            bo.setTitle("用户订单完成");
            bo.setMsgContent(msg);
            bo.setReceiverId(wxUserVo.getWxUserId());
            bo.setReceiverName(wxUserVo.getNickname());
            bo.setReceiverAvatar(wxUserVo.getAvatar());
            bo.setOrderId(vo.getOrderId());
            bo.setSpuName(vo.getSpuName());
            this.insertByBo(bo);
        }
    }

    /**
     * 律师超时通知
     * 尊敬的${lsName}律师，由于您没有积极响应查看客户${name}的订单详情，该订单已失效。
     */
    @Override
    public void orderReturnedMsg(SpuOrderAssignVo vo) {
        String msg = StrUtil.format("尊敬的{}律师，由于您没有积极响应查看客户{}的订单详情，该订单已失效。", vo.getLawFirmName(), vo.getUserName());
        WxUserVo wxUserVo = wxUserService.selectWxUserById(vo.getUserId());
        if(wxUserVo != null) {
            MessageBo bo = new MessageBo();
            bo.setTitle("用户订单完成");
            bo.setMsgContent(msg);
            bo.setReceiverId(wxUserVo.getWxUserId());
            bo.setReceiverName(wxUserVo.getNickname());
            bo.setReceiverAvatar(wxUserVo.getAvatar());
            //bo.setOrderId(vo.getOrderId());
            bo.setOrderId(Long.parseLong(vo.getTrackingNumber()));
            bo.setSpuName(vo.getSpuName());
            this.insertByBo(bo);
        }
    }

    /**
     * 微信用户注册消息
     */
    @Override
    public void wxUserRegisterMsg(WxUserVo vo) {
        String msg = "欢迎加入咕法网，专业律师团队伴您左右，法律难题轻松解决！";
        MessageBo bo = new MessageBo();
        bo.setTitle("欢迎消息");
        bo.setMsgContent(msg);
        bo.setReceiverId(vo.getWxUserId());
        bo.setReceiverName(vo.getNickname());
        bo.setReceiverAvatar(vo.getAvatar());
        bo.setOrderId(0L);
        bo.setSpuName("");
        this.insertByBo(bo);
    }
}
